package com.example.BluetoothTest;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.bluetooth.*;

import java.io.*;
import java.util.Vector;
import java.util.Timer;

//import java.util.logging.Logger;


public class BluetoothTestMidlet extends MIDlet 
   implements CommandListener {
    List main_list,dev_list;
    Command exit,ok;
    TextBox cmd;
    Display display;
    //private static java.util.Vector devices,services;
    private Timer Refreshtime = null;
    private BtInterfaceDisplay BtInterface;
    LocalDevice local;
    DiscoveryAgent agent;
    DataOutputStream dout;
    int currentDevice = 0;       //used as an indicator to the device queried for 
                                 //the echo server
    //private static Object lock=new Object();
    
public void startApp() {
    main_list = new List("Search Devices",Choice.IMPLICIT);   //the main menu
    dev_list  = new List("Select Device",Choice.IMPLICIT); //the list of devices
    cmd       = new TextBox("Text to echo","",120,TextField.ANY);
    exit      = new Command("Exit",Command.EXIT,1);
    ok        = new Command("Send",Command.OK,1);
    display   = Display.getDisplay(this);

    main_list.addCommand(exit);
    main_list.setCommandListener(this);
    dev_list.addCommand(exit);
    dev_list.setCommandListener(this);
    cmd.addCommand(ok);
    cmd.setCommandListener(this);
    
    main_list.append("Find devices",null);
    display.setCurrent(main_list);
        
    }
public void commandAction(Command com, Displayable dis) {
    if (com == exit){                                              //exit triggered from the main form
        destroyApp(true);
        notifyDestroyed();
    }
    if (com == List.SELECT_COMMAND){
        if (dis == main_list){                                     //select triggered from the main from
            if (main_list.getSelectedIndex() >= 0){                //find devices
            	//Refreshtime = new Timer();
            	//Refreshtime.schedule(FindDevices, 0, 2000);
                //FindDevices();
            	BtInterface = new BtInterfaceDisplay(this);
            	if(BtInterface == null)
            	{
            		do_alert("BTDiscover create failed", 400);
            	}
                //do_alert("Searching for devices...", Alert.FOREVER);
            }
        }
        if (dis == dev_list){                                      //select triggered from the device list
        	 /*StreamConnection conn = null;
          ServiceRecord service = (ServiceRecord)
                           services.elementAt(dev_list.getSelectedIndex());
           String url = service.getConnectionURL(
                                   ServiceRecord.NOAUTHENTICATE_NOENCRYPT,
                                  false);
            try {
                conn = (StreamConnection) Connector.open(url);       //establish the connection
                dout = new DataOutputStream(conn.openOutputStream());//Get the output stream
                display.setCurrent(cmd);                             //Show the textbox
            } catch (Exception e) {this.do_alert("Error Connecting" , 4000);}*/
    
        }
     }
    if(com == ok){                                                  //the user is sending a command
        try{
            dout.writeChars(cmd.getString() + "\n");
            dout.flush();
            cmd.setString("");
        } catch (Exception e) {this.do_alert("Error sending data" , 4000);} 
    }
}

public void do_alert(String msg,int time_out){
    if (display.getCurrent() instanceof Alert ){
        ((Alert)display.getCurrent()).setString(msg);
        ((Alert)display.getCurrent()).setTimeout(time_out);
    }else{
        Alert alert = new Alert("Bluetooth");
        alert.setString(msg);
        alert.setTimeout(time_out);
        display.setCurrent(alert);
    }
}

/** Shows main menu of MIDlet on the screen. */
void show() {
    Display.getDisplay(this).setCurrent(main_list);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {
	if(BtInterface != null)
	{
		BtInterface.destroy();
	}
}

}